<template>
    <div class="app-container details-content">
        <el-row v-loading="loading" class="details-box">
            <el-col :span="6" style="position: sticky;height: 100%;top: 0;">
                <div class="details-left">
                    <div class="text-title">
                        <div class="left">
                            <i class="el-icon-arrow-left" @click="handleGoBack"></i><span>
                                云文档
                            </span>
                        </div>
                        <i class="el-icon-notebook-2"></i>
                    </div>
                    <div class="text-head">
                        <div class="title">
                            {{ groupName || '' }}
                        </div>
                    </div>
                    <div class="text-search">
                        <el-input placeholder="搜索" v-model="filterText">
                            <i slot="prefix" class="el-input__icon el-icon-search"></i>
                        </el-input>
                    </div>
                    <div class="text-content">
                        <div class="top">
                            <div class="head">
                                目录
                            </div>
                            <div class="add">
                                <el-dropdown trigger="click" @command="handleCommand">
                                    <span class="el-dropdown-link">
                                        <i class="el-icon-plus" v-if="!editFlag"></i>
                                    </span>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item command="a" icon="el-icon-document">文档</el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>

                                <!-- <i class="el-icon-s-operation"></i> -->
                            </div>
                        </div>
                        <div class="directory">
                            <el-tree ref="tree" node-key="id" :data="knowMenuData" default-expand-all
                                :expand-on-click-node="false" :props="defaultProps" :filter-node-method="filterNode"
                                @node-click="handleNodeClick">
                                <span class="custom-tree-node menu_list" slot-scope="{ node, data }"
                                    style="height: 56px;line-height: 56px;">
                                    <span class="enumText" @dblclick.stop="editCateName(data, node)">
                                        <div ref="nodeLabel" @mouseover="nodeLabelover(node.label)"
                                            style="float: left;vertical-align: middle;width: 210px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
                                            {{ node.label || '未知名文档' }}
                                        </div>
                                        <i class="el-icon-plus" v-if="!editFlag"
                                            style="position: absolute;right:35px;margin-top: 19px;font-size: 18px;color:#2a2e33"
                                            @click.stop="handleDataAdd(node, data)">
                                        </i>
                                        <el-dropdown :hide-on-click="false"
                                            style="position:absolute;font-size:18px;right:10px;" v-if="!editFlag">
                                            <span class="el-dropdown-link">
                                                <i class="el-icon-more" style="margin-top: 19px;"
                                                    @click.stop="mapClick()"></i>
                                            </span>
                                            <el-dropdown-menu slot="dropdown">
                                                <el-dropdown-item @click.native="handleReviewName(node, data)">
                                                    重命名</el-dropdown-item>
                                                <el-dropdown-item @click.native="handleDelete(node, data)">
                                                    删除</el-dropdown-item>
                                                <el-dropdown-item v-if="!articleStatus"
                                                    @click.native="handleSaveKnow('', 2, data)">
                                                    发布</el-dropdown-item>
                                            </el-dropdown-menu>
                                        </el-dropdown>
                                    </span>
                                </span>
                            </el-tree>
                        </div>
                    </div>
                </div>
            </el-col>
            <el-col :span="18" v-loading="pageLoading" class="details-right-box">
                <div class="details-right">
                    <div class="top">
                        <div class="lf">
                            <p class="nav">
                                <span>{{ groupName || '' }}</span><i class="el-icon-arrow-right"></i><span
                                    style="color: #333;">{{
            knowData.groupName || '未知名文档' }}</span>
                            </p>
                        </div>
                        <div class="rt">
                            <el-button @click="handleSelectArticleStatus('read')" v-if="!articleStatus && !editFlag">
                                预览
                            </el-button>
                            <el-button @click="handleSelectArticleStatus('edit')" v-if="articleStatus && !editFlag">
                                编辑
                            </el-button>
                            <el-button @click="handleSaveKnow('', 2, currentMenuData)"
                                v-if="!editFlag && !articleStatus && currentMenuData.state != 2"
                                :disabled="!knowMenuData.length">
                                发布
                            </el-button>
                            <el-button type="primary" @click="handleSaveKnow('', 1)" :disabled="!knowMenuData.length"
                                v-if="!editFlag && !articleStatus && currentMenuData.state != 2">暂存</el-button>
                            <el-button type="primary"
                                v-if="!editFlag && !articleStatus && currentMenuData.state == 2 && knowMenuData.length"
                                @click="handleSaveKnow('', 2)">保存</el-button>
                        </div>
                    </div>
                    <div class="banner">
                        <img :src="coverImg" alt="">
                        <span class="upload" @click="handleGetVal" v-if="!editFlag">编辑图片</span>
                    </div>
                    <div class="page-right" style="display: flex;" v-if="!articleStatus">
                        <!-- 编辑器 DOM -->
                        <div v-if="knowMenuData.length"
                            style="border: 1px solid #ccc; flex: 1; width: calc(100vw - 370px); z-index: 100; /* 按需定义 */">
                            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor"
                                :defaultConfig="toolbarConfig" :mode="mode" />
                            <Editor style="height: 500px; overflow-y: hidden;" v-model="html" @onChange="onChange"
                                :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" />
                        </div>

                        <!-- 标题目录 -->
                        <div style="width: 200px; background-color: #f1f1f1;" v-if="knowMenuData.length">
                            <ul id="header-container" ref="headerContainer"></ul>
                        </div>
                    </div>
                    <div class="wrapper-main" v-show="articleStatus" style="display: flex;">
                        <div class="my-menus" v-show="navList.length">
                            <p :class="['item', i === currentMenu ? 'active' : '']" v-for="(item, i) in navList"
                                :key="i" @click="scrollToEle(item, i)" :style="`margin-left:${item.hLevel * 6}px;`">
                                {{ item.title }}
                            </p>
                        </div>
                        <div id="editor-container" ref="editorContainer" v-html="knowData.content"></div>
                    </div>
                    <div class="file-content" v-if="knowMenuData.length">
                        <el-button type="primary" plain icon="el-icon-plus" size="mini" v-show="!articleStatus"
                            @click="handleFile">上传附件</el-button>
                        <div class="file-list" v-if="fileList.length">
                            <div class="file-list-title">附件列表</div>
                            <el-table :data="fileList" border style="width: 100%" :row-style="{ height: '0' }">
                                <el-table-column prop="date" label="文件名称">
                                    <template slot-scope="scope">
                                        <a style="cursor: pointer;" class="file-item-name"
                                            :href="httpurl + scope.row.annex" target="_blank">
                                            {{ scope.row.annexName }}</a>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="address" label="操作" width="120">
                                    <template slot-scope="scope">
                                        <el-button type="text"
                                            @click="downloadFile(scope.row, scope.$index)">下载</el-button>
                                        <el-button type="text" v-if="!articleStatus"
                                            @click="deleteFile(scope.$index)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                    <div class="like_content">
                        <div class="like" :style="knowUserLike ? '' : 'border: 2px solid #009fd7'">
                            <img src="@/assets/images/know/like.png" alt="" @click="handleAddLike(1)"
                                v-show="!knowUserLike">
                            <img src="@/assets/images/know/like_check.png" alt="" @click="handleAddLike(0)"
                                v-show="knowUserLike">
                        </div>
                        <div class="like-item">
                            <div v-for="(item, i) in knowLikeUserList" :key="i" class="item-main">
                                <span class="avatar" :style="item.backgroundColor"> {{
            item.createBy[0] || '' }}</span>
                                <span class="like-name">{{ item.createBy }}</span>
                            </div>
                        </div>
                    </div>
                    <div class="comment">
                        <div class="comment-list">
                            <div class="comment-title" :style="commentList.length ? '' : 'margin-bottom: 12px'">
                                全文评论
                            </div>
                            <div class="comment-item" v-for="(item, i) in commentList" :key="i">
                                <div class="lf">
                                    <span :style="item.backgroundColor">
                                        {{ item.createBy[0] || '' }}
                                    </span>
                                </div>
                                <div class="center">
                                    <p style="padding-bottom: 12px;">
                                        <span class="name">{{ item.createBy }}</span>
                                        <span class="time">{{ item.createTime }}</span>
                                    </p>
                                    <p class="comment-content"><span v-if="item.commentedUserId" class="reply-user"
                                            :style="item.commentedUserId == createBy ? '' : 'width:auto;color:#1456f0;background:transparent'">
                                            @{{ item.commentedUserId }}</span>{{ item.content }}</p>
                                    <div class="like"></div>
                                </div>
                                <div class="comment-tool">
                                    <i class="el-icon-edit" @click="handleReply(item)"></i>
                                    <i class="el-icon-delete" @click="removeComment(item.id)"></i>
                                </div>
                            </div>
                        </div>
                        <div class="comment-save">
                            <div class="input-val">
                                <el-input placeholder="请输入内容" ref="autoFocus" v-model.trim="comment" clearable>
                                </el-input>
                            </div>
                            <div class="comment-btn" v-show="comment">
                                <el-button type="info" size="mini" plain @click="comment = ''">取消</el-button>
                                <el-button type="primary" size="mini" @click="handleAddComment">发送</el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
        <el-drawer title="我是标题" :visible.sync="isCover" :with-header="false">
            <div class="cover clearfix">
                <div v-for="(item, i) in coverList" :key="i" class="cover-item">
                    <img :src="item" alt="" @click="handleSelectImgs(item)">
                </div>
            </div>
        </el-drawer>
        <el-dialog title="文章目录名称" :close-on-click-modal="false" @close="handleClose" :visible.sync="centerDialogVisible"
            width="30%" center>
            <div>
                <el-form @submit.native.prevent :model="ruleForm" :rules="rules" ref="ruleForm" label-width="60px"
                    class="demo-ruleForm">
                    <el-form-item label="名称" prop="groupName">
                        <el-input v-model="ruleForm.groupName"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editSave">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 添加或修改OSS对象存储对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="文件名">
                    <el-upload class="upload-demo" :headers="headers"
                        :action="httpurl + '/customUploadApplet/formdata/upfileAnnex'" :data="uploadData"
                        :before-upload="beforeFileUpload" :on-preview="handlePreview" :on-remove="handleRemove"
                        :before-remove="beforeRemove" :on-success="uploadSuccessFile" multiple :file-list="uploadList">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip"></div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { SlateNode } from '@wangeditor/editor'
import { getToken } from "@/utils/auth";
import { upload, addKnow, delKnow, getKnowCatalog, getKnowDetail, getLikeList, getCommentList, delComment, addComment, addLike, updateKnow } from '@/api/staging/know'
import { Boot } from '@wangeditor/editor'
import attachmentModule from '@wangeditor/plugin-upload-attachment'
Boot.registerModule(attachmentModule)
export default {
    name: "list",
    components: { Editor, Toolbar },
    data() {
        return {
            uploadList: [],
            files: [],
            uploadData: {
                FFILE: "",
                annexName: ''
            },
            headers: {
                Authorization: "Bearer " + getToken(),
            },
            // 按钮loading
            buttonLoading: false,
            httpurl: process.env.VUE_APP_BASE_API,
            editorConfig: {
                placeholder: "请输入内容...",
                // autoFocus: false,
                // 所有的菜单配置，都要在 MENU_CONF 属性下
                MENU_CONF: {
                    uploadImage: {
                        server: process.env.VUE_APP_BASE_API + '/customUploadApplet/my/upload',
                        timeout: 5 * 1000, // 5s

                        fieldName: 'file',
                        allowedFileTypes: ["image/*"],
                        metaWithUrl: false, // 参数拼接到 url 上
                        // 自定义增加 http  header
                        headers: {
                            // Accept: 'text/x-json',
                            // otherKey: 'xxx'
                            Authorization: "Bearer " + getToken(),
                        },

                        maxFileSize: 10 * 1024 * 1024, // 10M
                        withCredentials: true,
                        base64LimitSize: 5 * 1024, // 5kb 以下插入 base64

                        onBeforeUpload(files) {
                            console.log('onBeforeUpload', files)

                            return files // 返回哪些文件可以上传
                            // return false 会阻止上传
                        },
                        onProgress(progress) {
                            console.log('onProgress', progress)
                        },
                        onSuccess(file, res) {
                            console.log('onSuccess', file, res)
                        },
                        onFailed(file, res) {
                            alert(res.message)
                        },
                        // 自定义插入图片
                        customInsert(res, insertFn) {
                            if (res.code === 200) {
                            } else {
                            }
                            insertFn(res.url, res.originalFilename, res.url);
                        },
                        onError(file, err, res) {
                            alert(err.message)
                            console.error('onError', file, err, res)
                        }
                    },
                    // 视频上传
                    uploadVideo: {
                        fieldName: "file",
                        server: process.env.VUE_APP_BASE_API + '/customUploadApplet/my/upload',

                        // 单个文件的最大体积限制，默认为 10M
                        maxFileSize: 5000 * 1024 * 1024, // 500M

                        // 最多可上传几个文件，默认为 5
                        maxNumberOfFiles: 3,
                        // 选择文件时的类型限制，默认为 ['video/*'] 。如不想限制，则设置为 []
                        allowedFileTypes: ["video/*"],

                        // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
                        meta: {
                            // token: 'xxx',
                            // otherKey: 'yyy'
                        },

                        // 将 meta 拼接到 url 参数中，默认 false
                        metaWithUrl: false,

                        // 自定义增加 http  header
                        headers: {
                            // Accept: 'text/x-json',
                            // otherKey: 'xxx'
                            Authorization: "Bearer " + getToken(),
                        },

                        // 跨域是否传递 cookie ，默认为 false
                        withCredentials: true,

                        // 超时时间，默认为 30 秒
                        timeout: 3000 * 1000, // 1000 秒,
                        // 上传之前触发
                        onBeforeUpload(file) {
                            return file;
                        },
                        // 自定义插入视频
                        customInsert(res, insertFn) {
                            // 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
                            // 先关闭等待的Message
                            if (res.code === 200) {
                            } else {
                                // Message.error({
                                //   message: `${res.data.originalName} 上传失败，请重新尝试`,
                                // });
                            }
                            insertFn(res.url, res.url);
                        },
                        // 上传进度的回调函数
                        onProgress(progress) {
                            console.log(progress);
                            // onProgress(progress) {       // JS 语法
                            // progress 是 0-100 的数字
                        },

                        // 单个文件上传成功之后
                        onSuccess(file, res) {
                            // alert(res.url)
                            console.log(`${file.name} 上传成功`, res, "aaaaa");
                            // this.$message({
                            //   message: "视频上传成功",
                            //   type: "success",
                            // });
                        },

                        // 单个文件上传失败
                        onFailed(file, res) {
                            console.log(`${file.name} 上传失败`, res);
                            // this.$message.error("错了哦" + res);
                        },

                        // 上传错误，或者触发 timeout 超时
                        onError(file, err, res) {
                            console.log(`${file.name} 上传出错`, err, res);
                            // this.$message.error("错了哦" + err);
                        },
                    },
                    uploadAttachment: {
                        customUpload(file, insertFn) {
                            upload(file).then(res => {   //upload是上传附件接口
                                console.log(res, 'res==')
                                insertFn(file.name, res.url)
                            });
                        }
                    }
                },
                hoverbarKeys: {
                    attachment: {
                        menuKeys: ['downloadAttachment']
                    }
                }
            },
            uploadObjs: {
                type: 'flie'
            },
            currentMenu: 0,
            menuList: [],
            knowMenu: [],
            editor: null,
            html: '<p>hello</p>',
            toolbarConfig: {
                insertKeys: {
                    index: 0, // 自定义插入的位置
                    keys: ['uploadAttachment'], // “上传附件”菜单
                },
                hoverbarKeys: {
                    attachment: {
                        menuKeys: ['downloadAttachment'], // “下载附件”菜单
                    },
                },
            },
            mode: 'default', // or 'simple'
            navList: [],
            centerDialogVisible: false,
            ruleForm: {
                groupName: '',
            },  // 新建知识库弹框信息
            rules: {
                groupName: [
                    { required: true, message: '请输入文章目录名称', trigger: 'blur' }
                ]
            }, // 表单验证
            editFlag: false,
            pageLoading: false,
            articleStatus: true,
            commentedUserId: '',
            comment: '', // 评论
            commentList: [], // 评论列表
            knowLikeUserList: [],
            knowUserLike: false,
            isCover: false,
            markDownContentVal: '',
            coverImg: require("@/assets/images/know/output (2).jpg"),
            groupName: '',
            coverList: [
                require("@/assets/images/know/output (2).jpg"),
                require("@/assets/images/know/output (3).jpg"),
                require("@/assets/images/know/output (4).jpg"),
                require("@/assets/images/know/output (5).jpg"),
                require("@/assets/images/know/output (6).jpg"),
                require("@/assets/images/know/output (7).jpg"),
                require("@/assets/images/know/output (8).jpg"),
                require("@/assets/images/know/output (9).jpg"),
                require("@/assets/images/know/output (10).jpg"),
                require("@/assets/images/know/output (11).jpg"),
                require("@/assets/images/know/output (12).jpg"),
                require("@/assets/images/know/output (13).jpg"),
            ],
            showTreeTool: false,
            disabledTooltip: false,
            knowData: {}, // 知识库详情
            knowMenuData: [],
            data: [{
                groupName: '首页',
                children: [{
                    groupName: '二级 2-1',
                    children: []
                }, {
                    groupName: '二级 2-2',
                    children: []
                }]
            }],
            defaultProps: {
                children: 'children',
                label: 'groupName'
            },
            searchVal: '',
            KNOW_ID: '',
            add: false,
            del: false,
            edit: false,
            filterText: '',
            fileList: [],
            isEdit: -1,
            currentMenuData: {},
            cateNameInput: '', // 动态绑定输入框中的值
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                file: [
                    { required: true, message: "文件不能为空", trigger: "blur" }
                ]
            },

            // 弹出层标题
            title: "",
            // 弹出层标题
            type: 0,
            // 是否显示弹出层
            open: false,
            loading: false	//加载状态
        };
    },
    watch: {
        filterText(val) {
            this.$refs.tree.filter(val);
        }
    },
    computed: {
        // 点赞背景色
        randomRgb() {
            return function () {
                let colorList = [
                    "#533980", "#335292", "#009fd7", "#b12d80", "#85327e", "#ea5c2e", "#89c8c1"
                ]
                let index = Math.floor(Math.random() * colorList.length)
                return {
                    backgroundColor: colorList[index]
                };
            }
        },
        createBy() {
            return this.$store.state.user.name
        }
    },
    mounted() {
        this.init()
    },
    methods: {
        uploadSuccessFile(res, file) {
            if (res.success == 1) {
                this.files.push({
                    annexName: res.annexName,
                    annex: res.fileName,
                    name: res.annexName,
                    url: res.url
                });
                console.log(this.files);
            }
        },
        beforeFileUpload(file) {
            const vm = this;
            vm.uploadData.FFILE = file;
            vm.uploadData.annexName = file.name;
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.uploadList = [];
            this.files = [];
            this.reset();
        },
        /** 提交按钮 */
        submitForm() {
            this.open = false;
            this.fileList = this.fileList.concat(this.files);
            this.uploadList = [];
            this.files = [];
        },
        // 表单重置
        reset() {
            this.form = {
                file: undefined,
            };
            this.resetForm("form");
        },
        /** 文件按钮操作 */
        handleFile() {
            this.reset();
            this.open = true;
            this.title = "上传文件";
            this.type = 0;
        },
        /** 图片按钮操作 */
        handleImage() {
            this.reset();
            this.open = true;
            this.title = "上传图片";
            this.type = 1;
        },
        onCreated(editor) {
            this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
        },
        handlerMenu() {
            let content = this.$refs.editorContainer;
            let els = content.querySelectorAll("h1,h2,h3,h4,h5,h6")
            let menus = []
            if (els) {
                els.forEach((item, index) => {
                    let menu = {}
                    menu.isActive = null
                    // 增加一个id标识
                    menu.title = item.innerText
                    menu.scrollTop = item.offsetTop
                    let level = item.tagName.toLowerCase().replace("h", "")
                    menu.level = parseInt(level)
                    item.setAttribute("id", `menus_${index + 1}`)
                    menu.id = `#menus_${index + 1}`
                    menus.push(menu)

                })
            }
            this.menuList = menus
            this.listenScroll()
        },
        // 监听目录导航，设置选中时的样式
        listenScroll() {
            window.addEventListener("scroll", () => {
                if (this.menuList) {
                    this.menuList.forEach((item, index, list) => {
                        let scrollTop = (document.documentElement.scrollTop || document.body.scrollTops) + 2
                        if (index == 0 && scrollTop >= item.scrollTop && scrollTop < list[index + 1]
                            .scrollTop) {
                            item.isActive = true

                        } else if (index > 0 && index < list.length - 1 && scrollTop >= item.scrollTop &&
                            scrollTop < list[index + 1].scrollTop) {
                            item.isActive = true
                        } else if (index === list.length - 1 && scrollTop >= item.scrollTop) {
                            item.isActive = true
                        } else {
                            item.isActive = false
                        }
                    })
                }

            })
        },
        getContentDirTree(htmlData) {
            if (!htmlData) {
                return [];
            }
            let hDomList = htmlData.match(
                /<h[1-6]{1}[^>]*>([\s\S]*?)<\/h[1-6]{1}>/g
            );
            if (!Array.isArray(hDomList)) {
                return [];
            }
            const dirTree = [];
            let preDir;
            hDomList.forEach((hDom, index) => {
                const startIndex = hDom.indexOf("id=\'");
                const endIndex = hDom.indexOf("\>")
                if (startIndex != -1 && endIndex != -1) {
                    const domId = hDom.slice(startIndex + 4, endIndex);
                    const re = /<h([1-6]{1})[^>]*>([\s\S]*?)<\/h[1-6]{1}>/
                    let hLevel = Number(hDom.replace(re, "$1"));
                    let titleContent = hDom.replace(re, "$2");
                    let title = titleContent.replaceAll(/<([\s\S]*?)>|<\/([\s\S]*?)>/g, "");
                    const currentDir = {
                        id: (index + 1),//用于点击的时候选中态
                        title,
                        domId,
                        hLevel
                    }
                    if (preDir) {
                        if (currentDir.hLevel > preDir.hLevel) {
                            currentDir.pid = preDir.id
                        } else if (currentDir.hLevel < preDir.hLevel) {
                            currentDir.pid = 0
                        } else {
                            currentDir.pid = preDir.pid
                        }
                    } else {
                        currentDir.pid = 0;
                    }
                    preDir = currentDir;
                    dirTree.push(currentDir)
                }
            })
            return dirTree;
        },
        // header数据
        navGenerate() {
            if (this.knowData.content) {
                let index = 1;
                let content = this.knowData.content
                this.knowData.content = content.replace(/<h[1-6]\b/ig, function (s) {
                    return s + " id='" + (index++) + "'";
                });
                // 示例使用
                const htmlString = this.knowData.content;
                const contentDirTree = this.getContentDirTree(htmlString);
                this.navList = contentDirTree
            } else {
                this.navList = []
            }
        },
        onChange(editor) {
            const headerContainer = this.$refs.headerContainer
            const headers = editor.getElemsByTypePrefix('header')
            headerContainer.innerHTML = headers.map(header => {
                const text = SlateNode.string(header)
                const { id, type } = header
                return `<li id="${id}" type="${type}">${text}</li>`
            }).join('')
            headerContainer.addEventListener('mousedown', event => {
                if (event.target.tagName !== 'LI') return
                event.preventDefault()
                const id = event.target.id
                editor.scrollToElem(id) // 滚动到标题
            })
        },
        scrollToEle(item, index) {
            this.currentMenu = index
            const section = document.getElementById(item.id);
            if (section) {
                section.scrollIntoView({ behavior: 'smooth' });
            }

        },
        // 关闭新增弹框
        handleClose() {
            this.centerDialogVisible = false;
            this.ruleForm = {
                groupName: ''
            }
            this.$refs.ruleForm.resetFields();
        },
        // 切换文章状态
        handleSelectArticleStatus(code) {
            if (code == 'edit') {
                if (!this.knowMenuData.length) {
                    this.$modal.msgWarning('请先添加知识目录')
                    return false
                }
                this.articleStatus = false
                const editor = this.editor
                if (editor == null) return
                editor.destroy() // 组件销毁时，及时销毁编辑器
                setTimeout(() => {
                    if (this.knowMenuData.length) {
                        // this.createEditorShow()
                    }
                }, 200)
            } else {
                if (window.editor && this.knowMenuData.length) {
                    const editor = this.editor
                    if (editor == null) return
                    editor.destroy() // 组件销毁时，及时销毁编辑器
                    this.handleSaveKnow('read', 1)
                    this.navGenerate()
                }
                this.articleStatus = true;

            }
        },
        // 返回上一级
        handleGoBack() {
            this.$router.go(-1)
        },
        // 删除评论
        removeComment(id) {
            delComment({ id }).then(response => {
                if (response.code == 200) {
                    this.comment = ''
                    this.$modal.msgSuccess('删除成功')
                    this.getUserComment()
                }
            });
        },
        // 回复评论
        handleReply(val) {
            this.commentedUserId = val.createBy
            this.commentedParentId = val.parentId
            this.$refs.autoFocus && this.$refs.autoFocus.focus();
        },
        // 发布评论
        handleAddComment() {
            let data;
            if (this.commentedUserId) {
                data = {
                    parentId: this.commentedParentId, knowBaseId: this.KNOW_ID, commentedUserId: this.commentedUserId, content: this.comment
                }
            } else {
                data = {
                    knowBaseId: this.KNOW_ID, createBy: this.createBy, content: this.comment
                }
            }
            addComment(data).then(response => {
                if (response.code == 200) {
                    this.comment = ''
                    this.getUserComment()
                }
            });
        },
        // 获取评论列表
        getUserComment() {
            getCommentList({ knowBaseId: this.KNOW_ID }).then(data => {
                if (data.code == 200) {
                    this.commentList = data.data.map(item => ({
                        ...item,
                        backgroundColor: this.randomRgb()
                    }))
                }
            });
        },

        // 点赞文章
        handleAddLike(likeupState) {
            let data = {
                knowBaseId: this.KNOW_ID, createBy: this.createBy, likeupState
            }
            addLike(data).then(response => {
                if (response.code == 200) {
                    this.getUserLike()
                }
            });
        },
        // 获取点赞列表
        getUserLike() {
            getLikeList({ knowBaseId: this.KNOW_ID }).then(data => {
                if (data.code == 200) {
                    if (data.data.length) {
                        this.knowLikeUserList = data.data.map(item => ({
                            ...item,
                            backgroundColor: this.randomRgb()
                        }))
                        let likeUser = data.data.filter(item => item.createBy == this.createBy)
                        this.knowUserLike = likeUser.length ? true : false
                    } else {
                        this.knowLikeUserList = []
                        this.knowUserLike = false
                    }
                }
            });
        },
        //失去焦点之后执行的方法
        editSave(val, data) {
            let param = {
                id: this.isEdit,
                groupName: this.ruleForm.groupName
            };
            updateKnow(param).then(data => {
                if (data.code == 200) {
                    this.getTreeData(1)
                    this.centerDialogVisible = false;
                    this.$message({
                        message: '操作成功',
                        type: 'success'
                    });
                } else {
                    this.$model.msgError("操作失败！");
                }
            });
        },
        // 切换封面
        handleSelectImgs(item) {
            this.coverImg = item;
            let param = { cover: this.coverImg, id: this.KNOW_ID }
            updateKnow(param).then(data => {
                if (data.code == 200) {
                    this.getTreeData(1)
                    this.$message({
                        message: '操作成功',
                        type: 'success'
                    });
                } else {
                    this.$model.msgError("操作失败！");
                }
            });
            this.isCover = false;

        },
        // tree节点过滤
        filterNode(value, data) {
            if (!value) return true;
            return data.groupName.indexOf(value) !== -1;
        },
        nodeLabelover() {
            this.showTreeTool = true
        },
        handleDataAdd(node, data) {
            if (data.state == 1) {
                this.$message({
                    message: '该文章暂未发布，请发布后再进行此操作！',
                    type: 'error'
                })
                return false
            }
            let params = {
                parentId: data.id, groupName: '', content: ''
            }
            addKnow(params).then(data => {
                if (data.code == 200) {
                    this.getTreeData(1)
                } else {
                    this.$model.msgError("操作失败！");
                }
            });
        },
        mapClick() { },
        handleReviewName(node, data) {
            this.centerDialogVisible = true
            this.ruleForm.groupName = data.groupName;
            this.isEdit = data.id;
        },
        // 删除文章
        handleDelete(node, data) {
            delKnow({ id: data.id }).then(data => {
                if (data.code == 200) {
                    this.getTreeData(2, 'del')
                    this.$message({
                        message: '操作成功',
                        type: 'success'
                    });
                } else {
                    this.$model.msgError("操作失败！");
                }
            });
        },
        // 保存知识库
        handleSaveKnow(flag = '', state, data = {}) {
            if (state == 2) {
                data.state = 2;
            }
            // const html = editor.getHtml()
            let param = { state, content: this.html, id: this.menuId, annexList: JSON.stringify(this.fileList) }
            updateKnow(param).then(data => {
                if (data.code == 200) {
                    this.getData(this.menuId)
                    if (!flag) {
                        this.$message({
                            message: '操作成功',
                            type: 'success'
                        });
                    }
                } else {
                    this.$model.msgError("操作失败！");
                }
            });
        },
        // 新增目录
        handleCommand() {
            let data = {
                parentId: this.KNOW_ID, groupName: '', content: ''
            }
            addKnow(data).then(response => {
                if (response.code == 200) {
                    if (this.knowMenuData.length) {
                        this.getTreeData(1)
                    } else {
                        this.getTreeData(2)
                    }
                    this.$message({
                        message: '操作成功',
                        type: 'success'
                    });
                } else {
                    this.$model.msgError("操作失败！");
                }
            });
        },
        handleGetVal() {
            this.isCover = true;
        },
        // 切换目录
        handleNodeClick(data, type = '', del) {
            this.menuId = data.id
            this.currentMenuData = data
            setTimeout(() => {
                if (type == 2 && del) {
                    this.getData(this.menuId, 'frist', del)
                } else {
                    if (!this.articleStatus && this.editor) {
                        this.editor.clear();
                    }
                    this.getData(this.menuId)
                }
            }, 200)
        },
        //初始执行
        init() {
            var FID = this.$route.query.FID;
            var edit = this.$route.query.editFlag;
            this.editFlag = edit == 'read' ? true : false;
            if (FID) {
                this.msg = 'edit';
                this.KNOW_ID = FID;
                this.menuId = FID;
                this.getCreateData(this.KNOW_ID)
                this.getTreeData(2)
            }
        },
        //下载
        downloadFile: function (item, index) {
            if (index > this.knowData.annexs.length - 1) {
                this.$message({
                    message: '请先保存后再进行文件下载',
                    type: 'error'
                });
                return false
            }
            this.$modal.confirm('确定要下载此文件吗？').then(() => {
                this.loading = true;
                window.location.href = this.httpurl + '/customUploadApplet/download?numId=' + index + '&id=' + this.menuId + '&urlPath=' + this.httpurl;
            }).finally(() => {
                this.loading = false;
            });
        },
        // 删除文件
        deleteFile(i) {
            this.$modal.confirm('确认删除？').then(() => {
                this.loading = true;
                this.fileList.splice(i, 1);
            }).finally(() => {
                this.loading = false;
            });
        },
        // 获取数据
        getData(id, type = '', del) {
            this.loading = true;
            this.fileList = []
            getKnowDetail({ id }).then(data => {
                this.loading = false;
                if (data.code == 200) {
                    this.html = data.data.content
                    this.knowData = data.data
                    let annexs = data.data.annexs?.map(item => ({
                        ...item,
                        type: item.annexName.split(".").pop()
                    }))
                    this.fileList = annexs ? annexs : []
                    this.navGenerate()
                    if (!type || del) {
                        if (window.editor) {
                            window.editor.destroy()
                        }
                    }
                } else {
                    this.$model.msgError("操作失败！");
                }
            });
        },
        // 首次获取数据
        getCreateData(id) {
            getKnowDetail({ id }).then(data => {
                if (data.code == 200) {
                    this.groupName = data.data.groupName
                    this.coverImg = data.data.cover ? data.data.cover : require("@/assets/images/know/output (2).jpg")
                    this.getUserLike()
                    this.getUserComment()
                    this.getData(this.menuId, 'frist');
                } else {
                    this.$model.msgError("操作失败！");
                }
            });
        },
        // 获取树结构目录
        getTreeData(node, type = '') {
            getKnowCatalog({ parentId: this.KNOW_ID }).then(data => {
                if (data.code == 200) {
                    if (data.data.length) {
                        this.knowMenuData = data.data
                        if (node == 2) {
                            this.$nextTick(() => {
                                this.$refs.tree &&
                                    this.$refs.tree.setCurrentKey(this.knowMenuData[0].id); //默认选中第一条
                                this.handleNodeClick(this.knowMenuData[0], node, type); //同时调用树点击事件
                            });
                        }
                    } else {
                        this.knowMenuData = []
                    }
                } else {
                    this.$model.msgError("操作失败！");
                }
            });
        }
    },
    beforeDestroy() {
        const editor = this.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时，及时销毁编辑器
    }
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" scoped>
.details-content {
    background-color: #f5f6f7;
    height: calc(100vh - 85px);

    .details-box {
        height: 100%;
    }

    .details-right-box {
        overflow: auto;
        height: 100%;
    }

    .details-left {
        padding: 30px 0px 40px 25px;

        .text-title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 16px;
            color: #22252b;
            padding-bottom: 30px;
            margin-right: 12px;

            .left {
                display: flex;
                align-items: center;

                i {
                    cursor: pointer;
                }
            }
        }

        .text-head {
            padding-left: 10px;

            .title {
                color: #2b2f34;
                font-size: 16px;
                text-align: left;
                padding-bottom: 12px;
            }

            .mark {
                width: 52px;
                height: 18px;
                font-size: 11px;
                display: flex;
                justify-content: center;
                align-items: center;
                border-radius: 5px;
                color: #356cf1;
                background-color: #cad6f7;
            }
        }

        .text-search {
            margin-top: 12px;
            padding: 0 6px;
        }

        .text-content {
            padding: 13px;

            .top {
                font-size: 14px;
                display: flex;
                padding-bottom: 8px;
                justify-content: space-between;
                align-items: center;
                color: #666;

                .el-icon-plus {
                    font-size: 16px;
                    margin-right: 8px;
                }

                .el-icon-s-operation {
                    font-size: 16px;
                }
            }
        }

        .el-icon-arrow-left {
            font-size: 22px;
            margin-right: 10px;
        }

        .el-icon-notebook-2 {
            font-size: 20px;
            color: #868b92;
        }
    }
}

.details-right {
    background-color: #fff;

    .top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10px 12px 8px 12px;

        .lf {
            color: #7c8188;
            font-size: 16px;
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            .nav {
                display: flex;
                align-items: center;
                // margin-bottom: 5px;
                font-size: 14px;

                .el-icon-arrow-right {
                    margin: 0 6px;
                }
            }
        }
    }

    .banner {
        height: 180px;
        position: relative;
        background-size: 100% 100%;

        img {
            width: 100%;
            height: 100%;
            object-fit: fill;
        }

        .upload {
            cursor: pointer;
            position: absolute;
            right: 38px;
            bottom: 10px;
            height: 26px;
            width: 68px;
            text-align: center;
            line-height: 26px;
            font-size: 14px;
            color: #fff;
            border: 1px solid #fff;
            border-radius: 5px;
        }
    }
}

.cover {
    padding: 0;

    .cover-item {
        width: 30%;
        height: 65px;
        margin: 5px;
        float: left;

        img {
            width: 100%;
            height: 100%;
            cursor: pointer;
        }
    }
}

.menu_list {

    .el-icon-plus,
    .el-icon-more {
        display: none;
    }
}

.menu_list:hover {}

.markDownDiv {
    z-index: 1 !important
}

.file-content {
    margin: 12px;

    .costs-uploadfile-div {
        position: relative;
        cursor: pointer;
        display: flex;
        align-items: center;
        /* margin: 12px; */
    }

    #textfield {
        width: 408px;
        height: 30px;
        margin-bottom: 0;
        cursor: pointer;
    }

    #FFILE {
        width: 408px;
        height: 30px;
        position: absolute;
        top: 0;
        margin-bottom: 0;
        left: 0;
        opacity: 0;
        cursor: pointer;
    }

    .file-list {
        padding: 6px;

        .file-list-title {
            padding: 12px 0;
            font-size: 15px;
        }
    }

    .file-item {
        margin-right: 18px;
        position: relative;

        a:hover {
            text-decoration: underline;
        }

        a {
            color: #8ca9eb;
        }

        .el-icon-circle-close {
            cursor: pointer;
            // position: absolute;
            right: -10px;
            top: -2px;
            color: #666;
            display: none;
        }

        .file-item-name {
            width: 200px;
            display: inline-block;
        }
    }

    .file-item:hover {
        .el-icon-circle-close {
            display: block;
        }
    }
}

.like_content {
    .like {
        cursor: pointer;
        width: 40px;
        height: 40px;
        border: 2px solid #d68e22;
        border-radius: 50%;
        text-align: center;
        line-height: 50px;
        margin: 80px auto 20px;

        img {
            width: 26px;
        }
    }

    .like-item {
        text-align: center;
        margin: auto;
        padding-bottom: 20px;
        display: flex;
        justify-content: center;

        .item-main {
            display: flex;
            margin: 0 2px;
            flex-direction: column;
            align-items: center;
        }

        .like-name {
            color: #7c8188;
            padding-top: 5px;
            display: inline-block;
        }

        .avatar {
            margin: 0 4px;
            height: 32px;
            width: 32px;
            text-align: center;
            line-height: 32px;
            display: inline-block;
            border-radius: 50%;
            color: #fff;
        }
    }
}

.comment {

    padding-right: 80px;

    .comment-save {
        display: flex;
        justify-content: flex-end;
        align-items: flex-end;
        flex-direction: column;
    }

    .input-val {
        width: 70%;
        padding-bottom: 16px;

    }

    .comment-btn {
        padding-bottom: 20px;
    }

    .comment-list {
        .comment-title {
            font-size: 24px;
            color: #000;
            padding-bottom: 12px;
            margin-left: 12px;
            border-bottom: 1px solid #dee0e3;
        }

        .comment-item {
            position: relative;
            padding: 12px;
            margin: 12px 0 12px 20px;
            display: flex;

            .lf {
                span {
                    margin: 0 4px;
                    height: 32px;
                    width: 32px;
                    text-align: center;
                    line-height: 32px;
                    display: inline-block;
                    border-radius: 50%;
                    color: #fff;
                }

                margin-right: 10px;
            }

            .center {
                .name {
                    padding-right: 5px;
                    color: #1f2329;
                }

                .time {
                    font-size: 12px;
                    color: #8f959e;
                }

                .reply-user {
                    color: #fff;
                    background-color: #1456f0;
                    width: 62px;
                    height: 22px;
                    line-height: 22px;
                    font-size: 13px;
                    text-align: center;
                    margin-right: 8px;
                    line-height: 21px;
                    border-radius: 10px;
                    display: inline-block;
                }
            }

            .comment-tool {
                position: absolute;
                display: none;
                top: 6px;
                right: 12px;

                i {
                    cursor: pointer;
                    font-size: 18px;
                    margin-left: 12px;
                }
            }
        }

        .comment-item:hover {
            border-radius: 8px;
            background-color: #eaeced;

            .comment-tool {
                display: block;
            }
        }
    }
}

.clearfix::after {
    content: "";
    display: table;
    clear: both;
}

label {
    margin-bottom: 0 !important;
}

p {
    margin-bottom: 0;
}

.el-tree {
    input {
        height: 32px;
        width: 100%;
    }

    background-color: transparent !important;

    ::v-deep .el-tree-node__content {
        height: 40px !important;
        margin-bottom: 3px;
        font-size: 14px;
    }

    ::v-deep .el-tree-node__content:hover {
        border-radius: 8px;
        font-size: 14px;
        color: #336df4 !important;
        background-color: #d4def6 !important;

        .el-icon-plus,
        .el-icon-more {
            display: block;
        }
    }

    ::v-deep .el-tree-node:focus>.el-tree-node__content {
        border-radius: 8px;
        font-size: 14px;
        color: #336df4 !important;
        background-color: #d4def6 !important;
    }

    ::v-deep .el-tree-node.is-current>.el-tree-node__content {
        border-radius: 8px;
        font-size: 14px;
        color: #336df4 !important;
        background-color: #d4def6 !important;
    }
}

#editor—wrapper {
    border: 1px solid #ccc;
    z-index: 100;
    /* 按需定义 */
}

#toolbar-container {
    border-bottom: 1px solid #ccc;
}

#editor-container {
    min-height: 300px;
    width: calc(100% - 240px);

    img {
        width: 100% !important;
    }
}

.my-menus {
    position: sticky;
    top: 0;
    height: 100%;
    padding: 12px 12px 0 0;
    width: 240px;

    .active {
        background-color: #6b8ad1;
        color: #fff;
        border-radius: 5px;
    }

    .item {
        cursor: pointer;
        margin: 3px 0;
        padding: 4px;
    }
}

.mdi-cloud-download {
    font-size: 16px;
    margin: 0 6px;
    color: #666;
}

.wrapper-main {
    padding: 12px 20px;
}

.el-table ::v-deep .el-table__body-wrapper .el-table__cell {
    padding: 0;
}
</style>
<style>
#editor-container img {
    width: 100%;
}

#header-container {
    list-style-type: none;
    padding-left: 20px;
}

#header-container li {
    color: #333;
    margin: 10px 0;
    cursor: pointer;
}

#header-container li:hover {
    text-decoration: underline;
}

#header-container li[type="header1"] {
    font-size: 20px;
    font-weight: bold;
}

#header-container li[type="header2"] {
    font-size: 16px;
    padding-left: 4px;
    font-weight: bold;
}

#header-container li[type="header3"] {
    font-size: 14px;
    padding-left: 8px;
}

#header-container li[type="header4"] {
    font-size: 12px;
    padding-left: 12px;
}

#header-container li[type="header5"] {
    font-size: 12px;
    padding-left: 16px;
}
</style>